/**
 * coding by 'UTF-8'
 *
 * 实验3 寄存器操作实现按键控制led流水灯的方向
 */

#include "stm32f10x.h"
void delay(unsigned int ms);
void GPIO_Config(void);
void LED0_Disp(unsigned char state);
unsigned char Key_Scan(void);
unsigned char key_val;
int main() {
    
    GPIO_Config();
    LED0_Disp(0);
    while (1) {
        key_val = Key_Scan();
        if (key_val == 1) {
            LED0_Disp(1);
        } else {
            LED0_Disp(0);
        }
    }
}

void LED0_Disp(unsigned char state) {
    if (state) {
        GPIOA->BRR |= GPIO_Pin_8; // PIN8 置0 LED亮
    } else {
        GPIOA->BSRR |= GPIO_Pin_8; // PIN8 置1 LED灭
    }
}

unsigned char Key_Scan() {
    unsigned char key_val = 0;
    if (!(GPIOC->IDR & GPIO_Pin_5)) {
        delay(1);
        key_val = 1;
    }

    return key_val;
}

void GPIO_Config() {

    // 开始APB2 GPIOA的时钟 led0对应GPIO
    RCC->APB2ENR |= 1 << 2;
    // 开始APB2 GPIOC的时钟 key对应GPIO
    RCC->APB2ENR |= 1 << 4;

    // 配置PIN8 为推完输出， 速度为50Hz的模式 led0
    GPIOA->CRH &= ~(0x3 << 2);
    GPIOA->CRH |= 0x3;

    // 配置PIN5 为浮空输入 01 00
    GPIOC->CRL |= 0x008;
}

void delay(unsigned int ms) {
    unsigned int i, j;

    for (i = 0; i < ms; i++)
        for (j = 0; j < 7992; j++)
            ;
}
